export type TreeOriginData<ID> = {
  id: ID;
  parentId: ID | 0;
};

export type TreeNode<T, ID> = T & {
  id: ID;
  parentId: ID | 0;
  children?: TreeNode<T, ID>[];
};

export const buildTreeByParentId = <T extends TreeOriginData<ID>, ID>(dataList: T[]): TreeNode<T, ID>[] => {
  const dataMap = new Map<T["parentId"], TreeNode<T, T["parentId"]>>();
  dataMap.set(0, { id: 0, parentId: 0 } as T);

  const childrenMap = new Map<T["parentId"], T[]>();
  dataList.forEach((item) => {
    // 绑定数据
    dataMap.set(item.id, item);

    // 绑定子节点
    const children = childrenMap.get(item.parentId);
    if (children) {
      children.push(item);
    } else {
      childrenMap.set(item.parentId, [item]);
    }
  });

  childrenMap.forEach((children, parentId) => {
    const node = dataMap.get(parentId);
    if (node) {
      node.children = children;
    } else {
      console.log("找不到父节点", parentId);
    }
  });
  return childrenMap.get(0) || [];
};
